/**
 ***********************************************************************************************************************
 * Copyright (c) 2020, China Mobile Communications Group Co.,Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * @file        tts_audio.c
 *
 * @brief       tts external API
 *
 * @revision
 * Date         Author          Notes
 * 2020-11-20   OneOS Team      First Version
 ***********************************************************************************************************************
 */

#include <oneos_config.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <os_dbg_ext.h>
#include "tts_url.h"
#include "tts_json.h"
#include "http_client.h"
#include "tts_audio.h"
#include "opencc_general.h"
#include "opencc_intf.h"

#include "os_errno.h"
#include "http_application_api.h"

#ifdef OS_USING_VFS
#include <vfs_posix.h>
#include <vfs_fs.h>
#endif

const char API_TTS_URL[] = "http://tsn.baidu.com/text2audio"; // 可改为https
const char API_TOKEN_URL[] = "http://openapi.baidu.com/oauth/2.0/token";
static struct tts_config g_config;


int tts_player(char *text, unsigned encoding)
{
    unsigned len = strlen(text);
    if (len == 0 || len > TTS_TEXT_MAX_LEN)
    {
        os_kprintf("no memory for create URI buffer.\n");
        return OS_ERROR;
    }


    opencc_info_t src;
    src.buf = (void*)text;
    src.buf_size = len;
    src.char_type =  CC_CHARC_TYPE_GBK;

    opencc_info_t *text_utf8;

    text_utf8 = opencc_character_conversion(&src, CC_CHARC_TYPE_UTF8);

    char obj[TTS_TEXT_MAX_LEN] = {0};
    UrlEncode((char*)text_utf8->buf, obj, TTS_TEXT_MAX_LEN);
    free(text_utf8->buf);
    free(text_utf8);
    //char obj[100] = "%E4%B8%AD%E7%A7%BB%E7%89%A9%E8%81%94%E7%BD%91%EF%BC%8C%E4%BD%A0%E5%A5%BD";

    http_client_t client = {0};
    http_client_data_t client_data = {0};

    char url[TTS_TEXT_MAX_LEN+200] = {0};
    char params_pattern[] = "%s?ctp=1&lan=zh&cuid=%s&tok=%s&tex=%s&per=%d&spd=%d&pit=%d&vol=%d&aue=%d";

    snprintf(url, sizeof(url) + sizeof(API_TTS_URL), params_pattern, API_TTS_URL, g_config.cuid, g_config.token, obj,
             g_config.per, g_config.spd, g_config.pit, g_config.vol, g_config.aue);

    http_client_get_file(&client, url, &client_data, TTS_AUDIO_FILE);

    //os_kprintf("start TTS_AUDIO_FILE.\n");

    wav_player(TTS_AUDIO_FILE);

    //unlink(TTS_AUDIO_FILE);

    return OS_EOK;
}

void tts_aivoice_config(const char *api_key, const char *secret_key)
{
    // 可以百度搜索"urlencode"
    char token[80] = "25.ed52c1ede0d0d27c25051092f23f54d4.315360000.1919127975.282335-22880206";
    
    if (vfs_mount("sd0", "/", "fat", 0, 0) == 0)
    {
        os_kprintf("Filesystem initialized!\n");
    }
    else
    {
        os_kprintf("Failed to initialize filesystem!\n");
    }

    // 将上述参数填入config中
    snprintf(g_config.api_key, sizeof(g_config.api_key), "%s", api_key);
    snprintf(g_config.secret_key, sizeof(g_config.secret_key), "%s", secret_key);
    snprintf(g_config.cuid, sizeof(g_config.cuid), "1234567C");

    char url_pattern[] = "%s?grant_type=client_credentials&client_id=%s&client_secret=%s";
    char url[200];
    snprintf(url, 200, url_pattern, API_TOKEN_URL, api_key, secret_key);
    os_kprintf("url is: %s\n", url);

    http_client_t client = {0};
    http_client_data_t client_data = {0};
    char *buf = NULL;
    buf = malloc(TTS_BUF_SIZE);
    memset(buf, 0, TTS_BUF_SIZE);

    http_client_get_file(&client, url, &client_data, "/tts_token.txt");

    int fd = open("/tts_token.txt", O_RDONLY);
    if (fd < 0)
    {
        os_kprintf("open txt failed!\n");
        return;
    }

    int length = read(fd, buf, TTS_BUF_SIZE);
    if (length > 0)
        os_kprintf("read length: %d\n",length);

    close(fd);
    unlink("/tts_token.txt");

    tts_parse_token(token, buf);

    if (buf != NULL)
    {
        free(buf);
    }

    snprintf(g_config.token, sizeof(token), "%s", token);
    os_kprintf("token is : %s\n", token);
    os_kprintf("config->token is : %s\n", g_config.token);

    g_config.per = 0;
    g_config.spd = 5;
    g_config.pit = 5;
    g_config.vol = 5;
    g_config.aue = 6;
    // aue对应的格式，format,OneOS just support wav.
    const char formats[4][4] = {"mp3", "pcm", "pcm", "wav"};
    snprintf(g_config.format, sizeof(g_config.format), formats[g_config.aue - 3]);

}

// 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，
// 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美
void tts_aivoice_per(int per)
{
    g_config.per = per;
}

// 语速，取值0-9，默认为5中语速
void tts_aivoice_spd(int spd)
{
    g_config.spd = spd;
}

// 音调，取值0-9，默认为5中语调
void tts_aivoice_pit(int pit)
{
    g_config.pit = pit;
}

// #音量，取值0-9，默认为5中音量
void tts_aivoice_vol(int vol)
{
    g_config.vol = vol;
}

// 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
void tts_aivoice_aue(int aue)
{
    g_config.aue = aue;
    // aue对应的格式，format
    const char formats[4][4] = {"mp3", "pcm", "pcm", "wav"};
    snprintf(g_config.format, sizeof(g_config.format), formats[aue - 3]);
}

//IMEI addresses are recommended
void tts_aivoice_cuid(char *cuid)
{
    snprintf(g_config.cuid, sizeof(g_config.cuid), cuid);
}
